"use strict";
const radon = require('radon');
const util = radon.util;
const Queue = require('./Queue.js');

class Mailer {
	constructor() {
		this.conf = null;
		this.from = null;
		this.sender = null;
		this.queue = null;

		this.setConf();
		this.setSender();
		this.setQueue();
	}
	setConf(conf) {
		this.conf = conf || radon.config('mail.smtp'); // Default config

		if (this.conf) {
			try {
				this.from = this.conf.auth.user;
			}
			catch (e) {
				util.log(104, 'Missing user(sender) in the mail SMTP config, please check config');

				radon.throw(100100);
			}
		}
		else {
			util.log(104, 'Missing the mail SMTP config, please check config');

			radon.throw(100100);
		}
	}
	setSender() {
		try {
			let nodeMailer = require('nodemailer');

			this.sender = nodeMailer.createTransport(this.conf);
		}
		catch (e) {
			util.log(104, 'Missing the nodemailer npm package, please install nodemailer');

			radon.throw(100101);
		}
	}
	setQueue() {
		let action = this.sender.sendMail.bind(this.sender);

		this.queue = new Queue(action, 1);
	}
	send(mail) {
		mail = {
			from: this.from,     // sender address
			to: mail.to,         // list of receivers
			cc: mail.cc,
			bcc: mail.bcc,
			subject: mail.subject,    // Subject line
			text: mail.text,          // plaintext body
			html: mail.html,          // html body
			attachments: mail.attachments
		};

		return this.queue.enQueue(mail);
	}
}

let m = new Mailer();

exports.conf = m.setConf.bind(m);
exports.send = m.send.bind(m);